home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 5610 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.1 KB

  1. Path: frco.com!usenet
  2. From: Jadam@tcmail.frco.com (Jim Adam)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: should operator== and operator= be virtual?
  5. Date: 5 Feb 1996 19:58:33 GMT
  6. Organization: Fisher Rosemount Systems
  7. Message-ID: <4f5nh9$e5p@rolaids.frco.com>
  8. References: <4ejvkr$btb@itnews.sc.intel.com>
  9. NNTP-Posting-Host: primrose.frco.com
  10. Mime-Version: 1.0
  11. X-Newsreader: WinVN 0.93.11
  12.  
  13. In article <4ejvkr$btb@itnews.sc.intel.com>, etse@scdt.intel.com says...
  14.  
  15. >Should operator==() and operator=() of a class be virtual if the class is
  16. >planned for extensibility? Personally I think in general assignement 
  17. >operators should be non-virtual, but I am not sure about equality operator.
  18. >Could anyone helps? Thanks.
  19.  
  20.  
  21. >class A {
  22. >public:
  23. >  A& operator=(const A&);
  24. >  virtual bool operator==(const A&) const;
  25. >  virtual bool operator!=(const A&) const;
  26. >};  
  27.  
  28.  
  29. >class B : public A {
  30. >public:
  31. >  B& operator=(const B&);
  32. >  
  33. >  virtual bool operator==(const A&) const; // ?
  34. >  virtual bool operator!=(const A&) const; // ?
  35. >
  36. >  virtual bool operator==(const B&) const; // ?
  37. >  virtual bool operator!=(const B&) const; // ?
  38.  
  39.  
  40. I think the virtual operator==() rarely makes sense. It implies
  41. either (a) that class B will use a different mechanism to compare
  42. the value of inherited member variables than class A would or
  43. (b) you consider it essential to always fully compare two B's
  44. together, and inside the operator==( const A&) you're going to
  45. do run-time type checking to determine if the argument is a B.
  46. If it is a B, you'll call the operator==( const B&) function.
  47. If not (maybe it's a C), you'll let the base class's equality
  48. operator handle the problem.  
  49.  
  50. --The real question, tho, is under what circumstances any of this 
  51. makes sense.  There, I think you have to decide based on your
  52. particular situation.  For me, I don't think I'd ever use it.
  53. If I do, say:
  54.  
  55.   list<A> somelist.
  56.   // ADD As, Bs, Cs, etc., to somelist
  57.   somelist.sort();
  58.  
  59. I expect the operator<() and operator==() defined on A to
  60. suffice.  Otherwise, maybe it's in the compare functor I
  61. pass to the sort function that all the RTTI stuff gets done,
  62. and not via virtual compare functions inside the classes.
  63.  
  64. Jim
  65.  
  66.